package com.ttdev.mmms.controller.login;

import com.ttdev.mmms.config.SecurityUtils;
import com.ttdev.mmms.entity.Admin;
import com.ttdev.mmms.repository.AdminRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * 杨培朔
 * 管理员
 *
 * 2019-12-13 19:34
 */
@Controller
@RequestMapping("/admin")
public class AdminLoginContoller {
    @Autowired
    private AdminRepository adminRepository;

    @PostMapping("/login")
    public String findByName(String username, String password, HttpSession session, RedirectAttributes attr){
        String pwd = SecurityUtils.md5Hex(password);//MD5技术加密
        Admin admin=adminRepository.findByName(username);
        if(admin!=null){
            if(admin.getPassword().equals(pwd)){
                session.setAttribute("admin",admin);
                //以秒为单位，即在没有活动90分钟后，session将失效
                session.setMaxInactiveInterval(90*60);
                return "redirect:/adminIndex";
            }else {
                attr.addFlashAttribute("error", "密码错误!");
                return "redirect:/";
            }
        }else {
            attr.addFlashAttribute("error", "账号不存在!");
            return "redirect:/";
        }
    }
}